﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Forum;
using ZHDJ.JoinParty.BLL;
using ZHDJ.WebPage;

namespace ZHDJ.Web.Portal.Forum
{
    public partial class BBSPost : DBPageBase
    {
        protected string TypeID
        {
            get
            {
                string result = string.Empty;
                if (!string.IsNullOrEmpty(Request.QueryString["TypeID"]))
                {
                    result = Request.QueryString["TypeID"];

                    result = StringHelper.RemoveHTML(result);
                }
                else
                {
                    if (!string.IsNullOrEmpty(ForumID))
                    {
                        var forum = DB.PartyForums.Find(ForumID);
                        if (forum != null)
                        {
                            return forum.TypeID;
                        }

                        result = string.Empty;
                    }

                }
                return result;
            }
        }

        /// <summary>
        /// 帖ID
        /// </summary>
        public string ForumID
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ForumID"]))
                    return Request.QueryString["ForumID"];
                return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin(true);
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            if (string.IsNullOrEmpty(TypeID) && string.IsNullOrEmpty(ForumID))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                    "<script>alert('论坛加载出错');UrlRefresh('../../BBSList.aspx?TypeID=" + this.TypeID + "');</script>");
                return;
            }
            ControlBusiness.ControlBindEx(this.ddlCategory, DB.PartyForumTypes.Where(a => a.IsShowIndex && a.ParentID!="").ToList(), "Title", "ID");

            if (!string.IsNullOrEmpty(ForumID))
            {
                var forum = DB.PartyForums.Find(ForumID);
                if (forum == null)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                        "<script>alert('论坛加载出错');UrlRefresh('BBSList.aspx?TypeID=" + this.TypeID + "');</script>");
                    return;
                }

                this.ddlCategory.Enabled = IsSystemAdministrator();

                labTitle.Text = forum.ForumTitle;
                this.txtDescription.Text = forum.ForumContent;
                this.txtTitle.Text = forum.ForumTitle;
                Label1.Text = "主题：";
                ddlCategory.SelectedValue = forum.TypeID;
                
            }
            else
            {
                Label1.Text = "主题：";
                ddlCategory.SelectedValue = this.TypeID;
               
            }
            
            if (ddlCategory.SelectedItem == null || ddlCategory.SelectedItem.Text.Trim()=="")
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                        "<script>alert('论坛加载出错');UrlRefresh('BBSIndex.aspx');</script>");
                return;
            }
            lblTitle2.Text = ddlCategory.SelectedItem.Text;

        }

        public void CheckddlCategory(string typeid)
        {
            if (ddlCategory.SelectedValue != typeid)
            {
                ddlCategory.SelectedValue = typeid.ToUpper();
            }
            if (ddlCategory.SelectedValue != typeid)
            {
                ddlCategory.SelectedValue = typeid.ToLower();
            }
        }

        /// <summary>
        /// 是否发贴人/管理员/版主
        /// </summary>
        /// <returns></returns>
        public bool IsSystemAdministrator()
        {
            bool isSystemAdministrator = false;

            if (IsSystemAdmin) //管理员
                isSystemAdministrator = true;
            else if (PartyForumTypeAdmin.IsForumTypeAdmin(this.TypeID, CurrentUser.LoginID))
                isSystemAdministrator = true;
            else
            {
                var type = DB.PartyForumTypes.Find(TypeID);
                if (type != null)
                {
                    if (PartyForumTypeAdmin.IsForumTypeAdmin(type.ParentID, CurrentUser.LoginID))
                        isSystemAdministrator = true;
                }

            }
            return isSystemAdministrator;
        }




        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRelease_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.ddlCategory.SelectedValue))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "<script>alert('版块类型不能为空！');</script>");
                return;

            }
            if (string.IsNullOrEmpty(txtTitle.Text) || string.IsNullOrEmpty(txtDescription.Text))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "<script>alert('主题或内容不能为空！');</script>");
                return;

            }
            if (string.IsNullOrEmpty(this.ForumID) &&
                !PartyForum.CanPostForum(CurrentUser.LoginID, DateTime.Now.AddMinutes(-15)))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "<script>alert('15分钟内只能发一次帖！');</script>");
                return;
            }
            if (CheckDescriptionWordText())
            {
                return;
            }

            PartyForum forum;
            if (string.IsNullOrEmpty(this.ForumID))
            {
                forum = new PartyForum();
                forum.ID = StringHelper.NewID;
                forum.ReplyTime = null;
                forum.ReplyCount = 0;
                forum.ReplyBy = "";
                forum.ReplyByName = "";
                forum.TodayReplyTimes = 0;
                forum.TodayVisitTimes = 0;
                forum.IsEssenceTime = null;
                forum.IsFirstTime = null;
                forum.IsFocusTime = null;
                forum.IsEssence = 0;
                forum.IsFirst= 0;
                forum.IsFocus = 0;
                forum.StatisticTime = DateTime.Now;
                forum.ForumCategory = "";
                forum.VisitTimes = 0;
                forum.CreateTime = DateTime.Now;
                forum.Author = CurrentUser.LoginID;
                forum.Source = 1;
                DB.PartyForums.Add(forum);
            }
            else
            {
                forum = DB.PartyForums.Find(ForumID);
                forum.ModifyTime = DateTime.Now;
            }
            forum.ForumTitle = txtTitle.Text;
            forum.ForumContent = txtDescription.Text;
            forum.TypeID = ddlCategory.SelectedValue;
            if (DB.SaveChanges() > 0)
            {


                if (string.IsNullOrEmpty(this.ForumID))
                {
                    //加分
                    PartyScoreHelper.Add(
                        () =>
                            PartyScoreHelper.AddForum(SysEnum.ForumScoreType.New, CurrentUser.LoginID,
                                CurrentUser.LoginID, forum.ID));
                    
                    PartyForum.RunForumTypeStatistics();
                    PartyForum.RunForumUserInfoStatistics(CurrentUser.LoginID);
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                        "<script>alert('帖子发表成功！');UrlRefresh(\"BBSReplyDetails.aspx?ForumID=" + forum.ID +
                        "\")</script>");
                }
                else
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                        "<script>alert('帖子编辑成功！');UrlRefresh(\"BBSReplyDetails.aspx?ForumID=" + forum.ID +
                        "\")</script>");
                }
            }
        }


        private bool CheckDescriptionWordText()
        {
            var list = DB.KeyWords.Where(a => txtDescription.Text.Contains(a.WordText)).ToList();
            if (list.Count > 0)
            {
                string strKW = "";
                list.ForEach(a =>
                {
                    string str = a.WordText;
                    strKW += "[" + str + "]";
                    this.txtDescription.Text = this.txtDescription.Text.Replace(str,
                        string.Format(@"<span style='background-color: rgb(255, 0, 0);'>{0}</span>", str));

                });
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk",
                    @"<script>alert('内容含有以下敏感词：\t\n" + strKW + "请马上修改！');</script>");
                return true;
            }
            else
            {
                return false;
            }
        }

        
    }
}